import asyncio, pyautogui, pyperclip, random

from core.utils import focus_wow, get_image_pos

class LoginRoleController():
    def __init__(self, role_name, extra_actions, ws_client, log_prefix):
        self.role_name = role_name
        self.log_prefix = log_prefix
        self.extra_actions = extra_actions
        self.ws_client = ws_client
        self.done = False
    
    async def start(self, only_login = False):
        focus_wow()
        await asyncio.sleep(1)
        await self.enter_role()
        if not only_login:
            await self.do_action()
            await self.exit_role()
    
    async def log(self, message, message_type=1):
        await self.ws_client.broadcast_log(message_content=f"{self.log_prefix} {message}", message_type=message_type)

    async def do_action(self):
        if self.done:
            await self.log("already done!", message_type=2)
            return
        await self.log("extra_actions start")
        await self.extra_actions(self.log_prefix)
        
    async def exit_role(self):
        await self.log("exit_role start")
        await asyncio.sleep(random.uniform(2, 3))
        pyautogui.press("f3")
        await asyncio.sleep(random.uniform(4, 5))
        search_bar_pos = await self.get_search_role_pos()
        if search_bar_pos is None:
            return
        await self.log("logout!")

    async def enter_role(self):
        await self.log("enter_role start")
        search_bar_pos = await self.get_search_role_pos()
        if search_bar_pos is None:
            self.run_callback()
            return
        await self.log("get search_bar_pos success")
        pyautogui.click(search_bar_pos)
        await asyncio.sleep(random.uniform(2, 2.5))
        pyperclip.copy(self.role_name)
        await asyncio.sleep(random.uniform(1, 1.5))
        pyautogui.hotkey('ctrl','v')
        pyautogui.press("enter")
        await asyncio.sleep(random.uniform(1.5, 2.5))
        pyautogui.click(x=search_bar_pos.x, y=search_bar_pos.y + 60)
        await asyncio.sleep(random.uniform(2.5, 3.5))
        pyautogui.press("enter")
        role_ready_pos = await self.get_role_ready_pos()
        if role_ready_pos is None:
            self.run_callback()
            return
        await self.log("enter_role success")
        await asyncio.sleep(random.uniform(1, 2))

    async def get_search_role_pos(self):
        count = 1
        pos = None
        while (pos is None) and (count < 10):
            await asyncio.sleep(1)
            pos = get_image_pos("images_2/search_bar_image.png", confidence=0.6)
            count += 1
        return pos
    
    async def get_role_ready_pos(self):
        count = 1
        pos = None
        while (pos is None) and (count < 60):
            await asyncio.sleep(1)
            pos = get_image_pos("images_2/word_login.png")
            count += 1
        return pos
    
    def run_callback(self):
        self.done = True